package com.dtlaya.allutils.dcmFileUpload.service;

import com.dtlaya.allutils.dcmFileUpload.config.DicomStorageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DicomStorageService {

    private final DicomParserService dicomParserService;
    private final DicomStorageProperties storageProperties;

    @Autowired
    public DicomStorageService(DicomParserService dicomParserService, 
                              DicomStorageProperties storageProperties) {
        this.dicomParserService = dicomParserService;
        this.storageProperties = storageProperties;
    }

    /**
     * 存储 DICOM 文件到自动生成的路径
     * @param dicomFile DICOM 文件
     * @return 存储的完整路径
     * @throws IOException 文件操作异常
     */
    public Path storeDicomFile(MultipartFile dicomFile) throws IOException {
        // 解析 DICOM 并生成存储路径
        Path storagePath = dicomParserService.parseAndGeneratePath(dicomFile);
        
        // 确保目录存在
        if (storageProperties.isAutoCreateDirs()) {
            Files.createDirectories(storagePath.getParent());
        }
        
        // 保存文件
        dicomFile.transferTo(storagePath);
        
        return storagePath;
    }

    /**
     * 批量存储 DICOM 文件
     * @param dicomFiles DICOM 文件数组
     * @return 存储路径列表
     */
    public List<Path> storeDicomFiles(MultipartFile[] dicomFiles) {
        return Arrays.stream(dicomFiles)
                .map(file -> {
                    try {
                        return storeDicomFile(file);
                    } catch (IOException e) {
                        throw new RuntimeException("存储文件失败: " + file.getOriginalFilename(), e);
                    }
                })
                .collect(Collectors.toList());
    }
}